import traceback

from schemas.database import SessionLocal
from schemas import crud, schemas


async def init_db():
    db = SessionLocal()
    try:
        # 初始化用户数据
        crud.create_user(db, user=schemas.UserCreate(username="admin", email="admin@example.com",
                                                     password="admin123", is_admin=True, point=200))
        crud.create_user(db, user=schemas.UserCreate(username="user", email="user@example.com",
                                                     password="user123", point=100))

        # 初始化订阅数据
        crud.create_subscription(db, subscription=schemas.SubscriptionCreate(name="基础订阅",
                                                                             description="基础功能订阅",
                                                                             email_subject="基础订阅通知",
                                                                             message_template="您的基础订阅消息：{content}",
                                                                             message_params="{\"content\": \"1\"}",
                                                                             points_cost=10))
        crud.create_subscription(db, subscription=schemas.SubscriptionCreate(name="高级订阅",
                                                                             description="高级功能订阅",
                                                                             email_subject="高级订阅通知",
                                                                             message_template="您的高级订阅消息：{content}",
                                                                             message_params="{\"content\": \"2\"}",
                                                                             points_cost=20))


        # 初始化管理员邮箱数据
        crud.create_admin_email(db,
                                admin_email=schemas.AdminEmailCreate(email="admin@smtp.com", username="ssss", password="smtp_password",
                                                                     smtp_server="smtp.example.com", smtp_port=587))

        db.commit()
        return "数据库初始化完成"
    except Exception as e:
        return f"初始化数据库时出错：{traceback.format_exc()}"
        db.rollback()
    finally:
        db.close()

#
# # 在应用启动时调用此函数
# init_db()
